import pygame
import random
import sys
import time

# 初始化pygame
pygame.init()

# 确保中文正常显示
pygame.font.init()
font_path = pygame.font.match_font('simsun')  # 尝试匹配中文字体
if not font_path:
    # 如果找不到中文字体，使用默认字体
    font_path = pygame.font.get_default_font()

# 游戏常量
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60
PLAYER_SPEED = 8
ITEM_SPEED = 5
ITEM_SPAWN_RATE = 30  # 每30帧生成一个物品
GAME_DURATION = 60  # 游戏时长60秒

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)

# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("方块收藏家")
clock = pygame.time.Clock()

# 玩家类
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface((50, 50))
        self.image.fill(BLUE)
        self.rect = self.image.get_rect()
        self.rect.centerx = SCREEN_WIDTH // 2
        self.rect.bottom = SCREEN_HEIGHT - 10

    def update(self):
        # 获取按键状态
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and self.rect.left > 0:
            self.rect.x -= PLAYER_SPEED
        if keys[pygame.K_RIGHT] and self.rect.right < SCREEN_WIDTH:
            self.rect.x += PLAYER_SPEED
        if keys[pygame.K_a] and self.rect.left > 0:  # 支持A键左移
            self.rect.x -= PLAYER_SPEED
        if keys[pygame.K_d] and self.rect.right < SCREEN_WIDTH:  # 支持D键右移
            self.rect.x += PLAYER_SPEED

# 物品类（方块和炸弹）
class Item(pygame.sprite.Sprite):
    def __init__(self, item_type):
        super().__init__()
        self.item_type = item_type  # 'cube' 或 'bomb'
        
        # 根据类型设置不同属性
        if item_type == 'cube':
            self.image = pygame.Surface((30, 30))
            self.image.fill(GREEN)
            self.value = 10  # 得分
        elif item_type == 'bomb':
            self.image = pygame.Surface((40, 40))
            self.image.fill(RED)
            self.value = -20  # 扣分
        elif item_type == 'bonus':
            self.image = pygame.Surface((35, 35))
            self.image.fill(YELLOW)
            self.value = 30  # 额外加分
        
        self.rect = self.image.get_rect()
        # 随机位置生成
        self.rect.x = random.randint(0, SCREEN_WIDTH - self.rect.width)
        self.rect.y = random.randint(-100, -40)  # 从屏幕上方外部生成

    def update(self):
        self.rect.y += ITEM_SPEED
        # 如果物品超出屏幕底部，则移除
        if self.rect.top > SCREEN_HEIGHT:
            self.kill()

# 创建精灵组
all_sprites = pygame.sprite.Group()
items = pygame.sprite.Group()

# 创建玩家
player = Player()
all_sprites.add(player)

# 游戏变量
score = 0
frame_count = 0
game_active = False
start_time = 0
high_score = 0

# 字体函数
def draw_text(surf, text, size, x, y, color=BLACK):
    font = pygame.font.Font(font_path, size)
    text_surface = font.render(text, True, color)
    text_rect = text_surface.get_rect()
    text_rect.centerx = x
    text_rect.centery = y
    surf.blit(text_surface, text_rect)

# 游戏主循环
running = True
while running:
    # 保持循环以正确的速度运行
    clock.tick(FPS)
    
    # 处理输入（事件）
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if not game_active and event.key == pygame.K_SPACE:
                # 开始新游戏
                game_active = True
                score = 0
                start_time = time.time()
                # 清空所有精灵
                for sprite in all_sprites:
                    if sprite != player:
                        sprite.kill()
                for sprite in items:
                    sprite.kill()
    
    if game_active:
        # 计算剩余时间
        elapsed_time = time.time() - start_time
        remaining_time = max(0, GAME_DURATION - elapsed_time)
        
        if remaining_time <= 0:
            # 游戏结束
            game_active = False
            if score > high_score:
                high_score = score
        
        # 生成物品
        frame_count += 1
        if frame_count % ITEM_SPAWN_RATE == 0:
            # 随机决定生成什么物品
            rand = random.random()
            if rand < 0.7:  # 70%概率生成方块
                item = Item('cube')
            elif rand < 0.95:  # 25%概率生成炸弹
                item = Item('bomb')
            else:  # 5%概率生成奖励方块
                item = Item('bonus')
            all_sprites.add(item)
            items.add(item)
        
        # 更新精灵
        all_sprites.update()
        
        # 碰撞检测
        hits = pygame.sprite.spritecollide(player, items, True)
        for hit in hits:
            score += hit.value
            # 确保分数不会低于0
            if score < 0:
                score = 0
    
    # 渲染
    screen.fill(WHITE)
    all_sprites.draw(screen)
    
    # 显示分数
    draw_text(screen, f"分数: {score}", 30, 100, 30)
    
    if game_active:
        # 显示剩余时间
        draw_text(screen, f"时间: {int(remaining_time)}", 30, SCREEN_WIDTH - 100, 30)
    else:
        # 显示开始界面和最高分
        draw_text(screen, "方块收藏家", 64, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 3)
        draw_text(screen, "按空格键开始游戏", 36, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
        draw_text(screen, f"最高分: {high_score}", 30, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 60)
        draw_text(screen, "使用左右方向键或A/D键移动", 24, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 120)
        draw_text(screen, "收集绿色方块加分，避开红色炸弹", 24, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 160)
        draw_text(screen, "黄色方块是奖励加分", 24, SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 200)
    
    # 翻转屏幕
    pygame.display.flip()

# 退出游戏
pygame.quit()
sys.exit()
